<template>
  <aside class="sidebar-ai" :class="{ 'ai-open': isAIOpen }">
    <div class="ai-header">AI助手</div>
    <div class="ai-chat">
      <div class="chat-message" v-for="(msg, idx) in chatMessages" :key="idx">
        {{ msg }}
      </div>
    </div>
    <div class="ai-input">
      <div class="input-group">
        <el-select v-model="modelSel" placeholder="模型切换" size="small" class="custom-change-btn">
          <el-option label="DeepSeek" value="deepseek-ai/DeepSeek-V3" :key="'deepseek-ai/DeepSeek-V3'"></el-option>
          <el-option label="通义千问" value="Qwen/Qwen3-8B" :key="'Qwen/Qwen3-8B'"></el-option>
        </el-select>
        <el-input v-model="chatInput" placeholder="输入问题hhh" clearable ref="inputRef" class="custom-input" @keyup.enter="sendMessage"></el-input>
        <el-button size="small" @click="sendMessage" class="custom-send-btn" :class="{ 'btn-loading': isLoading }">
          <span v-if="!isLoading">发送</span>
          <el-loading v-else indicator="el-icon-loading"></el-loading>
        </el-button>
      </div>
    </div>
  </aside>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue';
import { useAiChatStore } from '../../stores/aichatStroe';

// 定义组件Props
const props = defineProps({
  isAIOpen: {
    type: Boolean,
    default: false
  },
  // 可选：接收外部消息历史
  initialMessages: {
    type: Array,
    default: () => []
  }
});

// 定义组件Emits
const emit = defineEmits(['update:isAIOpen', 'messageSent', 'modelChanged']);

const userStore = useAiChatStore();
const chatInput = ref('');
const chatMessages = ref<string[]>(props.initialMessages);
const isLoading = ref(false);
const inputRef = ref(null);
const modelSel = ref('deepseek-ai/DeepSeek-V3'); // 新增：当前选中的模型

// 同步输入框和按钮高度的函数
const syncInputButtonHeight = () => {
  nextTick(() => {
    if (inputRef.value && inputRef.value.$el) {
      const inputEl = inputRef.value.$el.querySelector('.el-input__inner');
      const btnEl = document.querySelector('.custom-send-btn');

      if (inputEl && btnEl) {
        const inputHeight = inputEl.offsetHeight;
        btnEl.style.minHeight = `${inputHeight}px`;
        btnEl.style.paddingTop = '0';
        btnEl.style.paddingBottom = '0';
      }
    }
  });
};

// 与AI聊天交互
const sendMessage = async () => {
  const currentMessage = chatInput.value.trim();
  if (!currentMessage) return;

  // 添加用户消息到聊天记录
  chatMessages.value.push(`你：${currentMessage}`);
  chatInput.value = '';

  // 触发消息发送事件
  emit('messageSent', currentMessage);

  try {
    isLoading.value = true;
    // 发送消息时传递当前选中的模型
    console.log("当前模型---》", modelSel.value);
    await userStore.fetchAiChat(modelSel.value, currentMessage);
    chatMessages.value.push(`AI(${modelSel.value})：${userStore.content.text}`);
  } catch (error) {
    console.error('AI请求失败', error);
    chatMessages.value.push('AI：抱歉，请求失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

// 监听模型变化
watch(modelSel, (newValue) => {
  emit('modelChanged', newValue);
});

onMounted(() => {
  syncInputButtonHeight();

  // 监听窗口大小变化，动态调整高度
  window.addEventListener('resize', syncInputButtonHeight);

  // 组件卸载时移除监听器
  onUnmounted(() => {
    window.removeEventListener('resize', syncInputButtonHeight);
  });
});

// 监听isAIOpen变化（如果父组件控制）
watch(() => props.isAIOpen, (newValue) => {
  // 可以在这里添加响应逻辑
});
</script>

<style scoped>
/* 右侧AI栏样式 - 与原页面保持一致 */
.sidebar-ai {
  width: 0;
  border-left: 1px solid #ddd;
  background: #f8f9fa;
  overflow: hidden;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
}

.ai-open {
  width: 500px;
}

.ai-header {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
}

.ai-chat {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  min-height: 0;
}

.ai-input {
  padding: 15px;
  border-top: 1px solid #ddd;
}

/* 输入框组样式 */
.input-group {
  display: flex;
  align-items: stretch;
}

/* 自定义输入框样式 */
.custom-input {
  flex: 1;
  margin-right: -1px;
  /* 消除边框重叠 */
  border-radius: 4px 0 0 4px;
}

.custom-input .el-input__inner {
  border-right: none;
  /* 消除输入框右侧边框 */
  border-radius: 4px 0 0 4px;
}

/* 自定义发送按钮 */
.custom-send-btn {
  background-color: #4a4a4a;
  /* 深灰色背景 */
  border: 1px solid #333;
  /* 深灰色边框 */
  color: #fff;
  /* 白色文字 */
  padding: 0 15px;
  border-radius: 0 4px 4px 0;
  transition: all 0.3s;
  white-space: nowrap;
  /* 防止文字换行 */
  display: flex;
  align-items: center;
  justify-content: center;

  /* 悬停效果 */
  &:hover {
    background-color: #555;
    border-color: #444;
  }

  /* 点击效果 */
  &:active {
    background-color: #333;
    border-color: #222;
  }

  /* 加载状态 */
  &.btn-loading {
    cursor: not-allowed;
    opacity: 0.7;
  }
}

.custom-change-btn {
  width: 70px;
}
</style>
